// Describe: 展示设备信息
package cmd

import (
	"context"
	"github.com/olekukonko/tablewriter"
	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"os"
	"strconv"
	"wormhole/pkg/clientx"
	"wormhole/protos/hole"
)

var listCmd = &cobra.Command{
	Use:     "list",
	Aliases: []string{"ls"},
	Short:   "列出所有设备",
	Long:    `客户端命令`,
	Run: func(cmd *cobra.Command, args []string) {
		c, err := clientx.NewLocalClient()
		if err != nil {
			log.Fatal().Err(err).Send()
		}
		res, err := c.ListDevice(context.Background(), &hole.Empty{})
		if err != nil {
			log.Fatal().Err(err).Send()
		}
		if res == nil || len(res.Devices) == 0 {
			log.Fatal().Msg("本地服务端离线!")
		} else {
			devices := res.Devices
			state := map[int32]string{
				0: "offline",
				1: "online",
			}
			table := tablewriter.NewWriter(os.Stdout)
			table.SetHeader([]string{"index", "Ip", "Port", "Name", "State", "LastActiveTime"})
			for _, device := range devices {
				out := []string{
					strconv.Itoa(int(device.Key.Index)),
					device.Key.Ripple.Ip,
					strconv.Itoa(int(device.Key.Ripple.Port)),
					device.Key.Ripple.Name,
					state[device.StateCode],
					device.LastActiveTime,
				}
				rich := make([]tablewriter.Colors, len(out))
				if device.StateCode == 1 {
					rich[4] = tablewriter.Colors{tablewriter.Normal, tablewriter.FgCyanColor}
				} else {
					rich[4] = tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiRedColor}
				}
				table.Rich(out, rich)
			}
			table.Render()
		}
	},
}

func init() {
	rootCmd.AddCommand(listCmd)
}
